from django.shortcuts import render
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha

from django.http import HttpResponse,JsonResponse

from libs.yuntongxun.sms import CCP
from django import http
import random
import logging
logger = logging.getLogger('django')

# Create your views here.



from django.views import View

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpeg
        """


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpeg
        """
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, 300, text)

        # 响应图片验证码
        return HttpResponse(image, content_type='image/jpeg')

class SmsCodeView(View):

    def get(self,request,mobile):
        # 1. 获取请求参数
        image_code=request.GET.get('image_code')
        uuid=request.GET.get('image_code_id')
        # 2. 验证参数
        if not all([image_code,uuid]):
            return JsonResponse ({'code':400,'errmsg':'参数不全'})
        # 3. 验证图片验证码
        # 3.1 连接redis
        from django_redis import get_redis_connection
        redis_cli=get_redis_connection('code')
        # 3.2 获取redis数据
        redis_image_code=redis_cli.get('img_%s' % uuid)

        if redis_image_code is None:
            return JsonResponse ({'code':400,'errmsg':'图片验证码已过期'})
        # 3.3 对比
        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse ({'code':400,'errmsg':'图片验证码错误'})

        # 提取发送短信的标记，看看有没有
        send_flag=redis_cli.get('send_flag_%s'%mobile)

        if send_flag is not None:
            return JsonResponse ({'code':400,'errmsg':'不要频繁发送短信'})

        # 4. 生成短信验证码
        from  random import randint
        sms_code= '%06d'%randint(0,999999)

        logger.info(sms_code)
        # 保存短信验证码
        redis_cli.setex('sms_%s' % mobile, 300, sms_code)
        # 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)


        pipeline=redis_cli.pipeline()

        pipeline.setex(mobile,300,sms_code)

        # 添加一个发送标记.有效期 60秒 内容是什么都可以
        pipeline.setex('send_flag_%s' % mobile, 60, 1)

        pipeline.execute()

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '发送短信成功'})



